package com.wkk.authorization.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wkk.authorization.common.AuthorizationConstant;
import com.wkk.authorization.dto.AddOrUpdateRoleDto;
import com.wkk.authorization.entity.UmsRole;
import com.wkk.authorization.mapper.UmsRoleMapper;
import com.wkk.authorization.mapper.UmsUserRoleMapper;
import com.wkk.authorization.service.UmsRoleService;
import com.wkk.exception.NoBugException;
import com.wkk.utils.NoBugTools;
import com.wkk.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Set;

/**
 * @author : WangKeKe
 * @date : 2020/10/5 12:35
 * Description : 角色接口实现类
 */


@Service
@Slf4j
public class UmsRoleServiceImpl extends ServiceImpl<UmsRoleMapper, UmsRole> implements UmsRoleService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Set<String> queryRolesByUserId(String userId) {
        return new HashSet<>(baseMapper.queryUserRoles(userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrUpdateRole(AddOrUpdateRoleDto addOrUpdateRoleDto) {
        UmsRole umsRole = new UmsRole();
        umsRole.setName(addOrUpdateRoleDto.getName()).setStatus(addOrUpdateRoleDto.getStatus());
        if (NoBugTools.isNotEmpty(addOrUpdateRoleDto.getId())) {
            // 更新
            umsRole.setId(addOrUpdateRoleDto.getId());
            baseMapper.updateById(umsRole);
            log.info("修改角色信息角色ID：" + addOrUpdateRoleDto.getId());
            // 更新数据库缓存
            redisUtil.del(AuthorizationConstant.PERMISSION_CACHE_PREFIX + addOrUpdateRoleDto.getId());
            return true;
        }
        UmsRole role = baseMapper.selectOne(new LambdaQueryWrapper<UmsRole>()
                .eq(UmsRole::getName, addOrUpdateRoleDto.getName()));
        if (NoBugTools.isNotEmpty(role)) {
            throw new NoBugException("当前角色名已经存在");
        }
        baseMapper.insert(umsRole);
        return NoBugTools.isNotEmpty(umsRole.getId());
    }
}
